package com.msh.frame.web.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.msh.frame.common.util.StringUtil;
import com.msh.frame.web.util.HttpServletRequestUtil;
import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
import java.util.Map;

/**
 * 拦截request 获取PostData信息并放入request的attribute里
 */
public class RequestFilter implements Filter {

  @Override
  public void init(FilterConfig filterConfig) throws ServletException {

  }

  @Override
  public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
      FilterChain filterChain) throws IOException, ServletException {
    try {
      String body = HttpServletRequestUtil.getRequestPostData(servletRequest);
      if (StringUtil.isNotEmpty(body)) {
        JSONObject jsonObject = JSON.parseObject(body);
        for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
          servletRequest.setAttribute(entry.getKey(), entry.getValue());
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    filterChain.doFilter(servletRequest, servletResponse);
  }

  @Override
  public void destroy() {

  }
}
